import { Form, Input, message, Modal, TreeSelect } from "antd";
import { useEffect, useState } from "react";
import {
  apiAddDepartment,
  apiDepartmentsTree,
  apiModifyDepartment,
} from "~/api/department";
import type { IDepartment } from "~/types/manage/system/user";
import { transTreeToAntdTreeData } from "~/utils/ui.util";

interface Props {
  defaultParentId?: number;
  visible: boolean;
  department?: IDepartment | null;
  onCancel: () => void;
  onOk?: (values: Partial<IDepartment>) => void;
}

export default function DepartmentModal(props: Props) {
  const [form] = Form.useForm<Partial<IDepartment>>();
  const [treeData, setTreeData] = useState<IDepartment[]>([]);

  const _handler = {
    onCancel: () => {
      props.onCancel?.();
    },
    onOk: async () => {
      try {
        const fieldsValue = await form.validateFields();
        if (props.department?.id) {
          await apiModifyDepartment(props.department.id, fieldsValue);
        } else {
          await apiAddDepartment(fieldsValue);
        }
        props.onOk?.({
          id: props.department?.id,
          ...fieldsValue,
        });
      } catch (error: any) {
        message.error({
          content: error.message,
        });
      }
    },
  };

  const _fetch = {
    init: async () => {
      const resp = await apiDepartmentsTree();
      setTreeData([
        {
          label: "~ /",
          value: 0,
          title: "根节点",
        },
        ...transTreeToAntdTreeData(resp),
      ]);
    },
  };

  useEffect(() => {
    if (!props.visible) {
      return;
    }
    form.resetFields();
    if (props.defaultParentId) {
      form.setFieldValue("parentId", props.defaultParentId);
    }
    if (props.department) {
      form.setFieldsValue(props.department as any);
    }
  }, [props.department, props.visible, props.defaultParentId]);

  useEffect(() => {
    _fetch.init();
  }, []);

  return (
    <Modal
      title={props.department ? "编辑部门" : "新增子部门"}
      open={props.visible}
      maskClosable={false}
      onCancel={_handler.onCancel}
      onOk={_handler.onOk}
    >
      <Form form={form} layout={"vertical"}>
        <Form.Item label="父部门" name={"parentId"}>
          <TreeSelect
            showSearch
            placeholder="请选择父部门"
            allowClear
            treeDefaultExpandAll 
            treeLine={true}
            treeData={treeData}
            treeNodeLabelProp={"label"}
            disabled={!!props.defaultParentId}
          />
        </Form.Item>
        <Form.Item label="部门名称" name={"name"} required>
          <Input />
        </Form.Item>
        <Form.Item label="排序" name={"sort"}>
          <Input />
        </Form.Item>
        <Form.Item label="描述" name={"desc"}>
          <Input.TextArea />
        </Form.Item>
      </Form>
    </Modal>
  );
}
